import axios from 'axios'
import {setLOADING,getLOADING} from '../utils/utils'
// axios 配置
axios.defaults.timeout = 60000;//访问接口超出时间
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';//请求头设置
/*
*    多域名配置
*   1.mainURL：主域名 
*/
let domain = {
    mainURL:"http://122.114.222.22/",
    proxyTets:"api",
}

//POST传参序列化
axios.interceptors.request.use((config) => {
    if(!getLOADING().loadStatus){
        setLOADING({loadStatus:true})
    }
    return config;
},(error) =>{
    if(getLOADING().loadStatus){
        setLOADING({loadStatus:false})
    }
     _.toast("错误的传参", 'fail');
    return Promise.reject(error);
});

//返回状态判断
axios.interceptors.response.use((res) =>{
    if(!res.data.success){
        setTimeout(() => {
            setLOADING({loadStatus:false}) 
        }, 200);
        return Promise.resolve(res);
    }
    return res;
}, (error) => {
    if(getLOADING().loadStatus){
        setLOADING({loadStatus:false})
    }
    _.toast("网络异常", 'fail');
    return Promise.reject(error);
});

export function fetch(url, params={}) {
    return new Promise((resolve, reject) => {
        params.type = params.type?params.type:"post";
        axios[params.type](url, params)
        .then(response => {
            resolve(response.data);
        }, err => {
            reject(err);
        })
        .catch((error) => {
            reject(error)
        })
    })
}



//接口导出
export default {
    /*前端接口*/
    //第三方认证
    Test(){
        return fetch(domain.mainURL+'test.php',{type:"get"})
    },
    getData(){
        return fetch('http://localhost:3000/getdata',{type:"get"})
    }
}


